#pragma once

#include "util.hpp"
#include <iostream>
#include <unordered_map>
#include <mutex>
#include <websocketpp/server.hpp>
#include <websocketpp/config/asio_no_tls.hpp>

namespace liang
{
    using websocket_server = websocketpp::server<websocketpp::config::asio>;
    class onlineManager
    {
    public:
        // 进入大厅或房间
        void enterHall(uint64_t uid, websocket_server::connection_ptr &conn)
        {
            std::unique_lock<std::mutex> lock(_mutex);
            _hall_users.insert(std::make_pair(uid, conn));
        }
        void enterRoom(uint64_t uid, websocket_server::connection_ptr &conn)
        {
            std::unique_lock<std::mutex> lock(_mutex);
            _room_users.insert(std::make_pair(uid, conn));
        }
        // 退出大厅或房间
        void exitHall(uint64_t uid)
        {
            std::unique_lock<std::mutex> lock(_mutex);
            _hall_users.erase(uid);
        }
        void exitRoom(uint64_t uid)
        {
            std::unique_lock<std::mutex> lock(_mutex);
            _room_users.erase(uid);
        }
        // 判断是否在大厅或房间中
        bool isInHall(uint64_t uid)
        {
            std::unique_lock<std::mutex> lock(_mutex);
            auto it = _hall_users.find(uid);
            if (it == _hall_users.end()) return false;
            return true;
        }
        bool isInRoom(uint64_t uid)
        {
            std::unique_lock<std::mutex> lock(_mutex);
            auto it = _room_users.find(uid);
            if (it == _room_users.end()) return false;
            return true;
        }
        // 获取连接
        websocket_server::connection_ptr getConnFromHall(uint64_t uid)
        {
            std::unique_lock<std::mutex> lock(_mutex);
            auto it = _hall_users.find(uid);
            if (it == _hall_users.end()) return nullptr;
            return it->second;
        }
        websocket_server::connection_ptr getConnFromRoom(uint64_t uid)
        {
            std::unique_lock<std::mutex> lock(_mutex);
            auto it = _room_users.find(uid);
            if (it == _room_users.end()) return nullptr; 
            return it->second;            
        }

    private:
        std::mutex _mutex;
        std::unordered_map<uint64_t, websocket_server::connection_ptr> _hall_users; // id与大厅用户的映射
        std::unordered_map<uint64_t, websocket_server::connection_ptr> _room_users; // id与房间用户的映射
    };
}